package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @PackageName: com.itheima.security
 * @ClassName: SecurityController
 * @Author: zhangwendong
 * @Date: 2020/4/25 16:38
 * @Description: 安全控制框架
 */
@Component("SecurityController")
public class SecurityController implements UserDetailsService {

    @Reference
    private UserService userService;

    /*
    * @Description :spring 提供的安全框架,返回值为账号,密码,权限
    * @Date 21:47 2020/4/25
    **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.获取用户名,使用用户名去数据库中进行查询
        User user = userService.findByUserName(username);
        if(user == null){
            //return null;
            //通过抛出异常,在登录页面显示自定义错误
            throw new UsernameNotFoundException("用户名不存在");
        }
        //2.查询出的user中包含了用户的角色以及角色拥有的权限
        List<GrantedAuthority> list = new ArrayList<>();
        //获取该用户的角色
        Set<Role> roles = user.getRoles();
        if(roles != null && roles.size() > 0){
            //遍历
            for (Role role : roles) {
                //添加用户角色
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取角色拥有的权限
                Set<Permission> permissions = role.getPermissions();
                //遍历
                for (Permission permission : permissions) {
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
        }
        //创建框架的user对象
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
